package org.gd.hellojson.jackson.serializers;

import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.SerializerProvider;

import javax.xml.bind.annotation.XmlEnumValue;
import java.io.IOException;
import java.lang.reflect.Field;

/**
 * @author Gorhover
 * @version 1.0-SNAPSHOT
 * @since 2013-09-20 10:08
 */
public class XmlValueJsonSerializer extends JsonSerializer<Object> {

    @Override
    public void serialize(Object value, JsonGenerator jGen, SerializerProvider provider)
            throws IOException {
        Class clazz = value.getClass();
        if(clazz.isEnum()) {
            try {
                Field field = clazz.getField(((Enum) value).name());
                if(field.isAnnotationPresent(XmlEnumValue.class)) {
                    XmlEnumValue xmlEnumValue = field.getAnnotation(XmlEnumValue.class);
                    jGen.writeString(xmlEnumValue.value());
                }
            } catch (NoSuchFieldException e) {
                throw new IOException(e.getMessage(), e);
            }
        }


        if(String.class.equals(value.getClass())) {
            jGen.writeString(value + " [String]");
        }
        if(Integer.class.equals(value.getClass()) ||
                int.class.equals(value.getClass())) {
            jGen.writeNumber(((int) value) + 1);
        }
    }
}
